package com.mocha.bss.domain.org.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.coffee.core.CoffeeException;
import com.coffee.core.CoffeeResponseEnum;
import com.mocha.bss.domain.org.convert.AdmdivConvert;
import com.mocha.bss.domain.org.repository.AdmdivRepository;
import com.mocha.bss.domain.org.repository.entity.AdmdivEntity;
import com.mocha.bss.domain.rbac.repository.RoleAdmRepository;
import com.mocha.bss.org.vo.AdmdivTreeVO;
import com.mocha.bss.org.vo.AdmdivVO;
import com.pinghua.mocha.basics.dmo.AdmdivRedisBO;
import com.pinghua.mocha.basics.dmo.AdmdivTreeBO;
import com.pinghua.mocha.basics.setting.MochaSettings;
import com.pinghua.mocha.basics.setting.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 *
 * 区域信息
 *
 * @author songkui
 * @since 2025-03-24
 */

@Slf4j
@Service
@AllArgsConstructor
public class AdmdivService {

    private final AdmdivRepository admdivRepository;
    private final RedisTemplate<String, Object> redisTemplate;
    private final RoleAdmRepository roleAdmRepository;

    public List<AdmdivVO> listById(Long id){
        AdmdivEntity entity = admdivRepository.getById(id);
        if (null == entity || StrUtil.isEmpty(entity.getPath())){
            throw new CoffeeException(CoffeeResponseEnum.NotData);
        }
        return AdmdivConvert.INSTANCE.entityToVOList(admdivRepository.listByPath(entity.getPath()));
    }

    public List<AdmdivVO> listByParentId(Long parentId){
        List<AdmdivEntity> list = admdivRepository.lambdaQuery().eq(AdmdivEntity::getParentId, parentId).list();
        return AdmdivConvert.INSTANCE.entityToVOList(list);
    }

    public List<AdmdivVO> listInPath(String[] paths){
        List<AdmdivEntity> list = admdivRepository.lambdaQuery().in(AdmdivEntity::getPath, paths).list();
        return AdmdivConvert.INSTANCE.entityToVOList(list);
    }

    public List<AdmdivVO> filter(String[] paths){
        if (paths == null || paths.length == 0) return this.listByParentId(MochaSettings.DaZhou);
        if (paths.length == 1) {
            AdmdivEntity entity = admdivRepository.lambdaQuery().eq(AdmdivEntity::getPath, paths[0]).one();
            if (Objects.isNull(entity)) throw new CoffeeException(CoffeeResponseEnum.NotData);
            if (entity.getLevel() == 5) {
                List<AdmdivVO> list = new ArrayList<>();
                list.add(AdmdivConvert.INSTANCE.entityToVO(entity));
                return list;
            }
            return this.listByParentId(entity.getId());
        }
        return this.listInPath(paths);
    }

    public String[] getPaths(){
        return admdivRepository.getPaths(MochaSettings.DaZhou);
    }

    public void dataToRedis(){
        AdmdivEntity entity = admdivRepository.getById(MochaSettings.DaZhou);
        if (null == entity || StrUtil.isEmpty(entity.getPath())){
            throw new CoffeeException(CoffeeResponseEnum.NotData);
        }

        List<AdmdivEntity> list = admdivRepository.listByPath(entity.getPath());
        for (AdmdivEntity admEntity : list){
            AdmdivRedisBO admdivRedisBO = AdmdivConvert.INSTANCE.entityToRedisBo(admEntity);
            redisTemplate.opsForHash().put(RedisKeyConstant.ORG_ADMDIV_MAP, String.valueOf(admdivRedisBO.getCode()), admdivRedisBO);
        }

    }


    /** 通过用户获取 行政区划 如果用户已选择行政区划则 勾选 */
    public AdmdivTreeVO admdivTreeByUserId(Long userId){
        AdmdivTreeVO treeVO = admdivTreeVOByAll();
        if (null != userId){
            String admIds = roleAdmRepository.getAdmByRelatedId(userId);
            admIds = MochaSettings.ALL.equals(admIds) ? String.valueOf(MochaSettings.DaZhou) : admIds;
            checkAdm(admIds, treeVO);
        }
        return treeVO;
    }

    private void checkAdm(String admIds, AdmdivTreeVO vo){
        if (StrUtil.isEmpty(admIds)){
            return;
        }

        if (admIds.contains(String.valueOf(vo.getCode()))){
            vo.setChoose(true);
        }
        if (CollectionUtil.isEmpty(vo.getList())){
            return;
        }

        for (AdmdivTreeVO tv : vo.getList()){
            checkAdm(admIds, tv);
        }
    }

    public AdmdivTreeVO admdivTreeVOByAll(){
        AdmdivEntity entity = admdivRepository.getById(MochaSettings.DaZhou);
        if (null == entity || StrUtil.isEmpty(entity.getPath())){
            throw new CoffeeException(CoffeeResponseEnum.NotData);
        }
        List<AdmdivEntity> list = admdivRepository.listByPath(entity.getPath());

        return buildTree(entity, list);

    }

    private AdmdivTreeVO buildTree(AdmdivEntity parentEntity, List<AdmdivEntity> list) {
        AdmdivTreeVO admdivTree = AdmdivConvert.INSTANCE.entityToTreeVO(parentEntity);
        List<AdmdivEntity> childList = list.stream().filter(g -> parentEntity.getId().equals(g.getParentId())).toList();
        if (CollectionUtil.isEmpty(childList)) {
            return admdivTree;
        }

        List<AdmdivTreeVO> voList = new ArrayList<>();
        for (AdmdivEntity child : childList) {
            AdmdivTreeVO childNode = buildTree(child, list);
            voList.add(childNode);
        }

        admdivTree.setList(voList);
        return admdivTree;
    }



}

